package com.hcy.app.screen.relax

import android.text.TextPaint
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import androidx.hilt.navigation.compose.hiltViewModel
import com.hcy.app.LocalNavController
import kotlinx.coroutines.launch
import java.io.File
import java.util.regex.Pattern

@Composable
fun Book_Page(
    viewModel: RelaxViewModel = hiltViewModel(LocalContext.current as ComponentActivity)
){
    val navController = LocalNavController.current
    val ctx = LocalContext.current
    var showTools by remember { mutableStateOf(false) }
    val relaxState by viewModel.relaxState.collectAsState()
    val currentFile = File(relaxState.currentFile?.filePath.toString())
    // todo Text 分页测量还没弄、当前页和当前章节记录还没保存
    var currentChapter by remember { mutableIntStateOf(0) }
    var currentPage by remember { mutableIntStateOf(0) }
    var chapters = SplitChapters(currentFile)
    val screenWidth = LocalConfiguration.current.screenWidthDp
    val screenHeight = LocalConfiguration.current.screenHeightDp
    val maxWidth = LocalConfiguration.current.screenWidthDp

    var pages =  splitChaptersContent(chapters.get(currentChapter).content,maxWidth,30,TextPaint())
    val scope = rememberCoroutineScope() // 协程作用域
    AnimatedContent(
        targetState = relaxState.currentIndex,
        transitionSpec = {
            // 从左滑入或右滑入的动画
            if (targetState > initialState) {
                (slideInHorizontally { width -> width } + fadeIn()).togetherWith(
                    slideOutHorizontally { width -> -width } + fadeOut())
            } else {
                (slideInHorizontally { width -> -width } + fadeIn()).togetherWith(
                    slideOutHorizontally { width -> width } + fadeOut())
            }
        }
    ){index ->
        Box(
            modifier = Modifier.fillMaxSize().systemBarsPadding()
        ){
            if ( showTools ){
                // 工具栏
                Row(
                    modifier = Modifier.fillMaxWidth()
                        .zIndex(2f)
                        .background(Color(0xFF96D306)),
                    horizontalArrangement = Arrangement.End,
                ) {
                    IconButton(
                        content ={
                            Icon(
                                imageVector = Icons.Default.Home,
                                contentDescription = "首页",
                                tint = Color.White,
                                modifier = Modifier.size(30.dp)
                            )
                        },
                        onClick = {
                            navController.navigate("relax")
                        }
                    )
                }
            }
            // 内容区域
            val scrollState = rememberScrollState()
            Text(
                modifier = Modifier.fillMaxSize()
                    .padding(start=5.dp, end = 5.dp, bottom = 10.dp)
                    .background(Color(0xFFF7F8F4))
                    .verticalScroll(scrollState) // 启用垂直滚动
                    .pointerInput(Unit) {
                        detectTapGestures { offset ->
                            // offset 对应的是点击区域的位置，size 是当前页面的大小，受滚动效果影响，不是屏幕大小
                            Log.d("miao","点击区域,y:${offset.y},x:${offset.x},height:${screenHeight.dp.toPx()},width:${screenWidth.dp.toPx()}")
                            if ( offset.y > screenHeight.dp.toPx()*0.7 ){
                                if (offset.x > screenWidth.dp.toPx() * 0.75) {
                                    Log.d("miao", "右侧被点击:${index}")
                                    if (currentPage < pages.size ){
                                        currentPage++
                                        if ( currentPage >= pages.size && currentChapter < chapters.size ){
                                            currentChapter++
                                            pages = splitChaptersContent(chapters.get(currentChapter).content,maxWidth,30,TextPaint())
                                            currentPage =0
                                        }
                                        scope.launch {
                                            scrollState.scrollTo(0)
                                        }
                                    }
                                }
                                if ( offset.x < screenWidth.dp.toPx() * 0.25 ){
                                    Log.d("miao", "左侧被点击:${index}")
                                    if ( currentPage > pages.size || currentPage<1 ){
                                        if ( currentChapter>0 ){
                                            currentChapter--
                                            pages = splitChaptersContent(chapters.get(currentChapter).content,maxWidth,30,TextPaint())
                                            currentPage =0
                                        }
                                        scope.launch {
                                            scrollState.scrollTo(0)
                                        }
                                    }else{
                                        currentPage--
                                        scope.launch {
                                            scrollState.scrollTo(0)
                                        }
                                    }
                                }
                            }else {
                                Log.d("miao","showTools:${showTools}")
                                showTools = !showTools
                            }
                        }
                    },
                // todo 最后一页时可以选择回到列表页或者给出提示
                text = if (currentPage < pages.size ) pages[currentPage] else pages[pages.size-1]
            )
            // 底部章节列表
            if (showTools){
                val scrollState2 = rememberScrollState()
                Column(
                    modifier = Modifier.background(Color.Cyan)
                        .fillMaxHeight(0.7f)
                        .verticalScroll(scrollState2)
                        .align(Alignment.BottomStart)
                ) {
                    // 章节列表内容
                    chapters.forEach {
                        ListItem(
                            modifier = Modifier.clickable{
                                Log.d("miao","当前index:${it.index}")
                                currentChapter =it.index
                                pages = splitChaptersContent(chapters[currentChapter].content,maxWidth,30,TextPaint())
                                currentPage =0
                                showTools = false
                            },
                            headlineContent = {
                                Text(it.title)
                            }
                        )
                    }
                }
            }
        }
    }
}

data class Chapter(
    var index: Int = 0,
    var title: String = "",
    var content: String = "",
    var startIndex : Int =0,
    var endIndex: Int=0
)


// 将书按章节拆分
private fun SplitChapters(textFile: File): List<Chapter>{
    val fullText = textFile.readText(charset("GBK"))
    return extractChapters(fullText)
}
// 将章节拆分为页
private fun splitChaptersContent(content: String,screenWidth: Int, maxLines: Int,paint: TextPaint): List<String>{
    //todo 分页还有问题
    return TextPaging.getPages(content,screenWidth,maxLines,paint)
}
// 提取章节信息
fun extractChapters(text: String): List<Chapter> {
    // 正则表达式匹配常见的章节标题格式
    val pattern = Pattern.compile("^(第[0-9零一二三四五六七八九十百千]+(?:节|章|章节)\\s*.*)$", Pattern.MULTILINE)
    val matcher = pattern.matcher(text)

    var chapters =mutableListOf<Chapter>()
    var lastIndex = 0
    var lastChapterTitle = ""
    var index =0
    while (matcher.find()) {
        val chapterTitle = matcher.group(1) // eg: 第1节 重新做人 ,获取到的就是标题行
        val start = matcher.start()

        if ( lastIndex ==0 ){
            val content = text.substring(0,start)
            if (content.isNotEmpty()){

                chapters.add(Chapter(
                    index = index,
                    title = "序言",
                    content = content,
                    startIndex = lastIndex,
                    endIndex = start
                ))
            }
        }else{
            val content = text.substring(lastIndex, start)
            chapters.add(Chapter(
                index = index,
                title = lastChapterTitle,
                content = content,
                startIndex = lastIndex,
                endIndex = start
            ))
        }
        if (chapterTitle != null) {
            lastIndex = start+chapterTitle.length
            lastChapterTitle = chapterTitle
        }
        index++
    }

    // 添加最后一章的内容
    if (lastIndex != 0 && lastIndex < text.length) {
        chapters.add(Chapter(
            index = index,
            title = lastChapterTitle,
            content = text.substring(lastIndex),
            startIndex = lastIndex,
            endIndex = text.length
        ))
//        index++
    }

    return chapters
}